//
//  ViewController.swift
//  2.4.Creating a Service Within Your App With Action Extensions
//
//  Created by joker on 15/7/24.
//  Copyright (c) 2015年 joker. All rights reserved.
//

import UIKit
import MobileCoreServices

class ViewController: UIViewController {
    
    @IBOutlet weak var textField: UITextField!
    
    
    @IBAction func performShare(sender: UIBarButtonItem) {
        
        let controller = UIActivityViewController(activityItems: [textField.text], applicationActivities: nil)
        
        
        controller.completionWithItemsHandler = activityCompletionHandler
        presentViewController(controller, animated: true, completion: nil)
    }
    
    let type = kUTTypeText as  NSString as String
    
    func activityCompletionHandler(activityType: String!, completed: Bool, returnedItems: [AnyObject]!,activityError: NSError!) {
        if completed && activityError == nil {
            let item = returnedItems[0] as! NSExtensionItem
            if let attachments = item.attachments {
                let attachment = attachments[0] as! NSItemProvider
                if attachment.hasItemConformingToTypeIdentifier(type) {
                    attachment.loadItemForTypeIdentifier(type, options: nil,completionHandler: {[weak self](item: NSSecureCoding!, error: NSError!) in
                        let strongSelf = self!
                        if error != nil {
                            strongSelf.textField.text = "\(error)"
                        }
                        else {
                            if let value = item as?  NSString {
                                strongSelf.textField.text = value as String
                            }
                        }
                        })
                    
                }
            }
        }
    }
    
}

